from system.serializer import MenuSerializer


class MenuServer:
    def __init__(self):
        self.serializer = MenuSerializer

    # 解析重组查到的菜单扁平列表转为树列表
    def parse_tree(self, queryset):
        tree_list = queryset.values()
        tree_list_serializer = self.serializer(tree_list, many=True)

        def __parse(__tree_list, parent_id):
            tree_data = []
            for tree in __tree_list:
                if tree["parent_id"] == parent_id:
                    children = __parse(__tree_list, tree["id"])
                    if len(children) > 0:
                        tree["children"] = children
                    tree_data.append(tree)
            return tree_data

        return __parse(tree_list_serializer.data, 0)

